package ldh.im.server.websocket;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import ldh.im.server.websocket.initialize.WebSocketChannelInitializer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class WebSocketServerMain {

    private static final Logger LOGGER = LoggerFactory.getLogger(WebSocketServerMain.class);

    private int port;

    public WebSocketServerMain(int port) {
        this.port = port;
    }

    public void run() throws Exception {
        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            ChannelFuture webSocketChannelFuture = websocketServer(bossGroup, workerGroup, port);

            LOGGER.info("webSocketChannelFuture Start!!!");
            webSocketChannelFuture.channel().closeFuture().sync();
        } finally {
            workerGroup.shutdownGracefully();
            bossGroup.shutdownGracefully();
        }
    }

    private ChannelFuture websocketServer(EventLoopGroup bossGroup, EventLoopGroup workerGroup, int port) throws InterruptedException {
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup)
                .channel(NioServerSocketChannel.class)
                .childHandler(new WebSocketChannelInitializer())
                .option(ChannelOption.SO_BACKLOG, 128)
                .childOption(ChannelOption.SO_KEEPALIVE, true);

        ChannelFuture f = b.bind(port).sync();
        return f;
    }

    public static final void main(String[] args) throws Exception {
        int port = 9290;
        if (args.length > 0) {
            port = Integer.parseInt(args[0]);
        }

        try {
            new WebSocketServerMain(port).run();
        } catch (Exception e) {
            LOGGER.error("启动失败", e);
        }

    }
}
